﻿using AlarmModule.DbContexts;
using AlarmModule.Enums;
using AlarmModule.Models;
using LogModule.Interface;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Interop;

namespace AlarmModule.Interface.Implementation {
    // 报警订阅者（邮件/SMS/日志）
    public class LogAlarmNotifier : IAlarmSubscriber {
        //数据库上下文
        //private readonly AlarmDbContext _dbContext;
        private readonly ILogService _logger;
        public LogAlarmNotifier(ILogService logger) {
            _logger = logger;
        }
        /// <summary>
        /// 报警处理器实现
        /// </summary>
        /// <param name="tagName"></param>
        /// <param name="level">报警级别</param>
        public void HandleAlarm(string tagName, AlarmLevel level) {

            string subject = $"[{level}] 报警触发: {tagName}";
            var time = DateTime.Now;

            string body = $"时间: {time}\n级别: {level}\n请立即处理！";

            string MsgInfo = $"{tagName}:{level}:请立即处理";

            _logger.Warn($"{subject},{body}");

            // ✅ 关键：每次调用都创建新DbContext
            using (var dbContext = new AlarmDbContext(GetDbContextOptions())) {
                var alarm = new AlarmModel { Msg = MsgInfo, Time = time };
                try {
                    dbContext.AlarmModel.AddAsync(alarm);
                    dbContext.SaveChangesAsync();
                } catch (Exception ex) {
                    _logger.Error("报警信息持久化失败", ex);
                }
            }

            ////存储到数据库
            //AlarmModel alarm = new AlarmModel() { Msg = MsgInfo, Time = time };
            //try {
            //    _dbContext.AlarmModel.AddAsync(alarm);
            //    _dbContext.SaveChangesAsync();
            //} catch (Exception ex) {
            //    _logger.Error("报警信息持久化失败", ex);
            //}
            // // 邮件发送实现

        }
        private DbContextOptions<AlarmDbContext> GetDbContextOptions() {
            var optionsBuilder = new DbContextOptionsBuilder<AlarmDbContext>();
            optionsBuilder.UseSqlite("Data Source=D:\\Projects\\sqlite\\alarm.db;");
            return optionsBuilder.Options;
        }
    }
}
